#include "src\precompiled.h"
#include "src\file_system.h"
#include "src\texture.h"
#include "src\dialog.h"

texture::texture(const std::string &name, Bitmap *bmp, const matrix4 &tm, bool has_alpha)
	:	m_name(name + std::string(".dds")),
		m_bpp(32),
		m_tm(tm),
		m_has_alpha(has_alpha)
{
	if(!dialog::get_singleton().convert_textures())
		return;
	m_data.clear();
	m_width = bmp->Width();
	m_height = bmp->Height();
	BMM_Color_fl *row = new BMM_Color_fl[m_width];
	for(size_t i = 0; i < m_height; i++) {
		bmp->GetPixels(0, i, m_width, row);
		for(size_t j = 0; j < m_width; j++) {
			BYTE a = (BYTE)(row[j].a * 255);
			BYTE r = (BYTE)(row[j].r * 255);
			BYTE g = (BYTE)(row[j].g * 255);
			BYTE b = (BYTE)(row[j].b * 255);
			DWORD pixel = (a<<24)|(r<<16)|(g<<8)|(b);
			m_data.push_back(pixel);
		}
	}
	delete [] row;
}

void texture::save() const
{
	dialog *d = dialog::get_singleton_ptr();
	if(d->convert_textures()) {
		std::string path = file_system::get_singleton().get_path(PA_TEXTURES) + m_name;

		nvtt::InputOptions io;
		io.setTextureLayout(nvtt::TextureType_2D, m_width, m_height);
		io.setMaxExtents(4096);
		io.setRoundMode(nvtt::RoundMode_ToNextPowerOfTwo);
		io.setMipmapData(&m_data[0], m_width, m_height);

		if(d->generate_mipmaps())
			io.setMipmapGeneration(true);
		else
			io.setMipmapGeneration(false);

		nvtt::Format pf1, pf2;
		if(d->compression_method_option() == CM_DXT1)
			pf1 = pf2 = nvtt::Format_DXT1;
		else if(d->compression_method_option() == CM_DXT1_DXT3) {
			pf1 = nvtt::Format_DXT1;
			pf2 = nvtt::Format_DXT3;
		}
		else if(d->compression_method_option() == CM_DXT1_DXT5) {
			pf1 = nvtt::Format_DXT1;
			pf2 = nvtt::Format_DXT5;
		}
		else {
			pf1 = nvtt::Format_RGB;
			pf2 = nvtt::Format_RGB;
		}

		nvtt::CompressionOptions co;
		if(has_alpha())
			co.setFormat(pf2);
		else
			co.setFormat(pf1);

		nvtt::OutputOptions oo;
		oo.setFileName(path.c_str());

		nvtt::Compressor comp;
		comp.process(io, co, oo);
	}
}